package com.zzm.validate.validator;

import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.util.ValidatorUtils;

public class LengthValidator {

	/**
	 * 使用该验证方法必须在 配置xml中声明最大、最小长度
	 * 	<var>
			<var-name>minLength</var-name>
			<var-value>4</var-value>
		</var>
		<var>
			<var-name>maxLength</var-name>
			<var-value>10</var-value>
		</var>
	 * @param bean 被验证的bean
	 * @param field @see org.apache.commons.validator.Field
	 * @return true is in range, otherwise false.
	 */
	public static boolean validateLength(Object bean, Field field) {
		int minLength = Integer.parseInt(field.getVarValue("minLength"));
		int maxLength = Integer.parseInt(field.getVarValue("maxLength"));
		String value = ValidatorUtils.getValueAsString(bean, field.getProperty());
		return GenericValidator.isInRange(value.length(), minLength, maxLength);
	}
}
